package com.yss.netty.processor;

import com.yss.netty.protocol.CommandType;
import com.yss.netty.protocol.Message;
import com.yss.netty.protocol.SerType;
import com.yss.netty.util.serialize.ISerialize;
import com.yss.netty.util.serialize.JsonSerializeUtil;
import com.yss.pojo.NettyServerAck;
import io.netty.channel.Channel;


public abstract class AbstractHandlerProcessor {

    /**
     * Task processing logic
     *
     * @param commandType
     * @param channel
     * @param opaque
     * @param params
     */
    public void execute(final CommandType commandType, final Channel channel, final long opaque, final Object params) {
        ProcessorResultInfo handleResult = handle(commandType, params);

        if (handleResult == null || handleResult.getHandleResult() == null) {
            // The server must return results to avoid client read timeout
            byte[] body = new JsonSerializeUtil().serialize(NettyServerAck.builder().code(-1).msg(null).build());
            channel.writeAndFlush(Message.of(CommandType.SERVERACK, SerType.JSON, body, opaque));
            return;
        }

        ISerialize iSerialize = SerType.matchUtilBySerType(handleResult.getSerType());
        byte[] body = iSerialize.serialize(handleResult.getHandleResult());

        channel.writeAndFlush(Message.of(handleResult.getCommandType(), handleResult.getSerType(), body, opaque));
    }

    /**
     * Methods of subclassing business logic
     *
     * @param commandType
     * @param params
     * @return
     */
    public abstract ProcessorResultInfo handle(final CommandType commandType, final Object params);

}
